package com.heihei.utils.dto;

import com.alibaba.fastjson.JSONObject;
import com.baidu.unbiz.easymapper.MapperFactory;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.CollectionUtils;

import java.beans.FeatureDescriptor;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Bean转换工具类
 *
 */
public final class BeanUtil {
	/**
	 * 
	 * 方法描述 不copy为null的属性
	 */
	public static void copyPropertiesExcludeNull(Object source, Object target) {
		BeanWrapperImpl wrappedSource = new BeanWrapperImpl(source);
		String[] ignoreProperties = Stream.of(wrappedSource.getPropertyDescriptors()).map(FeatureDescriptor::getName).filter(propertyName -> wrappedSource.getPropertyValue(propertyName) == null)
				.toArray(String[]::new);
		BeanUtils.copyProperties(source, target, ignoreProperties);
	}

	/**
	 * 
	 * 方法描述  copy
	 */
	public static <A, B> B copy(A sourceObject, Class<B> targetClass) {
		return MapperFactory.getCopyByRefMapper().mapClass(sourceObject.getClass(), targetClass).registerAndMap(sourceObject, targetClass);
	}

	/**
	 * 
	 * 方法描述 copy
	 *
	 */
	public static <A, B> void copy(A sourceObject, B targetObject) {
		MapperFactory.getCopyByRefMapper().mapClass(sourceObject.getClass(), targetObject.getClass()).registerAndMap(sourceObject, targetObject);
	}

	/**
	 * 
	 * 方法描述 copy集合
	 *
	 */
	public static <A, B> List<B> copy(List<A> sourceList, Class<B> targetClass) {
		if (CollectionUtils.isEmpty(sourceList)) {
			return Collections.emptyList();
		}
		return sourceList.stream().map(e -> copy(e, targetClass)).collect(Collectors.toList());
	}

	/**
	 * 
	 * 方法描述  根据sort进行升序排列(仅适用于设备分类、物资分类等结构符合条件的返回结果)
	 *
	 */
	public static List<JSONObject> ascOrder(List<JSONObject> list) {
		return list.stream().sorted((obj, anotherObj) -> {
			Integer sort = obj.getInteger("sort") == null ? Integer.MAX_VALUE : obj.getInteger("sort");
			Integer anotherSort = obj.getInteger("sort") == null ? Integer.MAX_VALUE : anotherObj.getInteger("sort");
			return sort.compareTo(anotherSort);
		}).collect(Collectors.toList());

	}

}